package com.glamour.hlcity.componenet.task.factory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.glamour.hlcity.common.util.ListUtil;
import com.glamour.hlcity.component.task.api.CmdExecute;
import com.glamour.hlcity.component.task.api.CreateExecuteUnit;
import com.glamour.hlcity.component.task.api.ExecuteUnit;

public class TaskFactory implements ApplicationContextAware {
	
	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext=applicationContext;
	}
	
	/**
	 * 获得命令执行器
	 * @param type
	 * @return
	 */
	public ExecuteUnit executeUnit(String type){		
		return ListUtil.first(queryCmdExecute(type));
	}
	
	/**
	 * 获得执行单元生成器
	 * @return
	 */
	public List<CreateExecuteUnit> createExecuteUnit(){
		return queryCreateExecuteUnit();
	}
	
	/**
	 * 查询命令执行单元
	 * @param type 类型
	 * @return
	 */
	private List<ExecuteUnit> queryCmdExecute(String type){
		List<ExecuteUnit> list=new ArrayList<ExecuteUnit>();
		Map map=this.applicationContext.getBeansOfType(ExecuteUnit.class);
		for(Iterator<Map.Entry> iter=map.entrySet().iterator();iter.hasNext();){
			ExecuteUnit execute=(ExecuteUnit) iter.next().getValue();
			 if(execute.type().equals(type)){
				 list.add(execute);
			 }	 
		}
		return list;
	}
	
	private List<CreateExecuteUnit> queryCreateExecuteUnit(){
		List<CreateExecuteUnit> list=new ArrayList<CreateExecuteUnit>();
		Map map=this.applicationContext.getBeansOfType(CreateExecuteUnit.class);
		for(Iterator<Map.Entry> iter=map.entrySet().iterator();iter.hasNext();){
			CreateExecuteUnit execute=(CreateExecuteUnit) iter.next().getValue();
			list.add(execute);
		}
		return list;
	}

}
